﻿using HslCommunication;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static DataCapture.Helper.PublicHelp;
using System.Windows.Forms;
using System.Diagnostics;
using System.Data;
using DataCapture.Helper;

namespace DataCapture.DeviceDataSave
{
    class PlcPopulateData
    {
        private static PublicHelp.DeviceData<PublicHelp.RWTakeDataModel>[] DeviceRWTakeData = new PublicHelp.DeviceData<PublicHelp.RWTakeDataModel>[3];
        private static PublicHelp.RWTakeDataModel[] RWTakeData = new PublicHelp.RWTakeDataModel[3];

        private static PublicHelp.DeviceData<PublicHelp.RWTakeInfoDataModel>[] DeviceRWTakeInfoData = new PublicHelp.DeviceData<PublicHelp.RWTakeInfoDataModel>[2];
        private static PublicHelp.RWTakeInfoDataModel[] RWTakeInfoData = new PublicHelp.RWTakeInfoDataModel[2];

        private static PublicHelp.DeviceData<List<PublicHelp.RWTakeInfoDataModel>> DeviceRWLastListTakeInfoData = new PublicHelp.DeviceData<List<PublicHelp.RWTakeInfoDataModel>>();
        private static List<PublicHelp.RWTakeInfoDataModel> RWLastListTakeInfoData = new List<PublicHelp.RWTakeInfoDataModel>();

        private static PublicHelp.DeviceData<PublicHelp.ReportDataModel>[] DeviceReportData = new PublicHelp.DeviceData<PublicHelp.ReportDataModel>[40];
        private static PublicHelp.ReportDataModel[] ReportData = new PublicHelp.ReportDataModel[40];
        /// <summary>
        /// 保存任务数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="No"></param>
        /// <param name="device_id"></param>
        /// <param name="dataType"></param>
        /// <param name="ReadData"></param>
        /// <param name="RegisterNumber"></param>
        public static void RWTask_SaveData<T>(int No, string device_id, string dataType, T ReadData, int RegisterNumber)
        {

            int lengthPerPart = 20; // 10个字符串，这里应为10*2 = 20 
            switch (No)
            {
                case 0: device_id = "生产线_A"; break;
                case 1: device_id = "生产线_B"; break;
            }
            switch (RegisterNumber)
            {   
               
                case 20:
                    RWTakeData[No].lineId = device_id;
                    RWTakeData[No].taskNum = (ReadData as string).Substring(0, lengthPerPart).Replace("\u0000","" );
                    RWTakeData[No].taskTime = (ReadData as string).Substring(lengthPerPart, lengthPerPart).Replace("\u0000", "");
                    RWTakeData[No].startBoxNum = (ReadData as string).Substring(lengthPerPart * 2, lengthPerPart).Replace("\u0000", "");
                    RWTakeData[No].boxSpec = (ReadData as string).Substring(lengthPerPart * 3, lengthPerPart).Replace("\u0000", "");
                    RWTakeData[No].featureCode = (ReadData as string).Substring(lengthPerPart * 4, lengthPerPart).Replace("\u0000", "");
                    RWTakeData[No].length = (ReadData as string).Substring(lengthPerPart * 5, lengthPerPart).Replace("\u0000", "");
                    
                    if (int.TryParse((ReadData as string).Substring(lengthPerPart * 6, lengthPerPart).Replace("\u0000", ""), out int produceTotal))
                    {RWTakeData[No].produceTotal = produceTotal;}
                    else{RWTakeData[No].produceTotal = 0;}

                    if (int.TryParse((ReadData as string).Substring(lengthPerPart * 7, lengthPerPart).Replace("\u0000", ""), out int currentTotal))
                    {RWTakeData[No].currentTotal = currentTotal;}
                    else{RWTakeData[No].currentTotal = 0;}

                    //RWTakeData[No].produceTotal = int.Parse((ReadData as string).Substring(lengthPerPart * 6, lengthPerPart).Replace("\u0000", ""));
                    //RWTakeData[No].currentTotal = int.Parse((ReadData as string).Substring(lengthPerPart * 7, lengthPerPart).Replace("\u0000", ""));
                    RWTakeData[No].produceBatch = (ReadData as string).Substring(lengthPerPart * 8, lengthPerPart).Replace("\u0000", "");
                    
                    DeviceRWTakeData[No].timeStamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); ;
                    DeviceRWTakeData[No].deviceId = device_id;
                    DeviceRWTakeData[No].dataType = dataType;
                    DeviceRWTakeData[No].data = RWTakeData[No];

                    //转发数据
                    MQTTConsoleServer.Instance.ForwardData(DeviceRWTakeData[No], "TakeData");
                    break;
            }
        }

        /// <summary>
        /// 保存当前任务台账数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="No"></param>
        /// <param name="device_id"></param>
        /// <param name="dataType"></param>
        /// <param name="ReadData"></param>
        /// <param name="RegisterNumber"></param>
        public static void RWInfo_SaveData(DataTable dt,int No)
        {
            try
            {
                string device_id = "";
                switch (No)
                {
                    case 0: device_id = "生产线_A"; break;
                    case 1: device_id = "生产线_B"; break;
                   
                }
                if (dt.Rows.Count != 0)
                {
                    DataRow row = dt.Rows[dt.Rows.Count - 1]; //获取最新的任务行数据

                    RWTakeInfoData[No].lineId = device_id;                                  //生产线ID
                    RWTakeInfoData[No].taskNum = row["NO"].ToString();                      //任务编号
                    RWTakeInfoData[No].taskTime = row["ProductDate"].ToString();            //生产日期
                    RWTakeInfoData[No].startCaseNum = row["SIDBoxNo"].ToString();           //起始盒号
                    RWTakeInfoData[No].startBoxNum = row["SIDCaseNumBegin"].ToString();     //起始箱号
                    RWTakeInfoData[No].boxSpec = row["CasePreNum"] == DBNull.Value ? 0 : (int)row["CasePreNum"]; ;                //装箱规格
                    RWTakeInfoData[No].caseSpec = row["SanMaBoxPreNum"] == DBNull.Value ? 0 : (int)row["SanMaBoxPreNum"]; ;               //装盒规格
                    RWTakeInfoData[No].weight = row["Weight"].ToString();                   //每箱重量
                    RWTakeInfoData[No].featureCode = row["SIDFeatureNo"].ToString();        //特征码/机手号
                    RWTakeInfoData[No].length = row["SIDLineLenght"].ToString();            //脚线长度
                    RWTakeInfoData[No].goodsCode = row["ProductType"].ToString();           //物品类码
                    RWTakeInfoData[No].produceBatch = row["BatchesNum"].ToString();         //生产批次
                    RWTakeInfoData[No].corporationCode = row["CorporationCode"].ToString(); //企业代码
                    RWTakeInfoData[No].corporationName = row["CorporationName"].ToString(); //企业名称
                    RWTakeInfoData[No].sectionMask = row["SectionMask"].ToString();         //段别标志
                    RWTakeInfoData[No].detonatorName = row["ProductName"].ToString();       //雷管名称
                    RWTakeInfoData[No].material = row["MaterialType"].ToString();           //材质
                    RWTakeInfoData[No].power = row["MaterialWeiLi"].ToString();             //威力
                    RWTakeInfoData[No].category = row["ProductModel"].ToString();           //类别
                    RWTakeInfoData[No].FactoryModel = row["FactoryModel"].ToString();       //芯片厂家
                    RWTakeInfoData[No].notes = row["Remarks"].ToString();                   //备注
                    RWTakeInfoData[No].permit = row["Permit"].ToString();                   //许可证
                    RWTakeInfoData[No].SIDTaskNum = row["SIDTaskNum"] == DBNull.Value ? 0 : (int)row["SIDTaskNum"]; ;                 //生产总数
                    RWTakeInfoData[No].SIDCompleteNum = row["SIDCompleteNum"] == DBNull.Value ? 0 : (int)row["SIDCompleteNum"]; ;         //已生产数量
                    RWTakeInfoData[No].CurrentTime = ((DateTime)row["CurrentTime"]).ToString("yyyyMMdd"); ;               //当天使用时间
                    RWTakeInfoData[No].ShengYuQty = row["ShengYuQty"] == DBNull.Value ? 0 : (int)row["ShengYuQty"]; ;                 //已生产数量
                }
                else
                {
                    RWTakeInfoData[No] = new PublicHelp.RWTakeInfoDataModel();
                }
                DeviceRWTakeInfoData[No].timeStamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                DeviceRWTakeInfoData[No].deviceId = device_id;
                DeviceRWTakeInfoData[No].dataType = "Report";
                DeviceRWTakeInfoData[No].data = RWTakeInfoData[No];

                //转发数据
                MQTTConsoleServer.Instance.ForwardData(DeviceRWTakeInfoData[No], "TakeInfoData");
            }
            catch (Exception ex)
            {
                Log4NetHelper.Error($"处理任务台账数据异常！ex:{ex}",true);
            }
        }
        /// <summary>
        /// 保存当天所有任务台账数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="No"></param>
        /// <param name="device_id"></param>
        /// <param name="dataType"></param>
        /// <param name="ReadData"></param>
        /// <param name="RegisterNumber"></param>
        public static void RWListInfo_SaveData(DataTable dt, int No)
        {
            PublicHelp.RWTakeInfoDataModel RWTakeInfoData = new PublicHelp.RWTakeInfoDataModel();
            RWLastListTakeInfoData.Clear();
            try
            {
                string device_id = "";
                switch (No)
                {
                    case 0: device_id = "生产线_A"; break;
                    case 1: device_id = "生产线_B"; break;
                }
                if (dt.Rows.Count > 0)
                {
                    foreach (DataRow row in dt.Rows)
                    {
                        RWTakeInfoData.lineId = device_id;                                  //生产线ID
                        RWTakeInfoData.taskNum = row["NO"].ToString();                      //任务编号
                        RWTakeInfoData.taskTime = row["ProductDate"].ToString();            //生产日期
                        RWTakeInfoData.startCaseNum = row["SIDBoxNo"].ToString();           //起始盒号
                        RWTakeInfoData.startBoxNum = row["SIDCaseNumBegin"].ToString();     //起始箱号
                        RWTakeInfoData.boxSpec = row["CasePreNum"] == DBNull.Value ? 0 : (int)row["CasePreNum"]; ;                    //装箱规格
                        RWTakeInfoData.caseSpec = row["SanMaBoxPreNum"] == DBNull.Value ? 0 : (int)row["SanMaBoxPreNum"]; ;               //装盒规格
                        RWTakeInfoData.weight = row["Weight"].ToString();                   //每箱重量
                        RWTakeInfoData.featureCode = row["SIDFeatureNo"].ToString();        //特征码/机手号
                        RWTakeInfoData.length = row["SIDLineLenght"].ToString();            //脚线长度
                        RWTakeInfoData.goodsCode = row["ProductType"].ToString();           //物品类码
                        RWTakeInfoData.produceBatch = row["BatchesNum"].ToString();         //生产批次
                        RWTakeInfoData.corporationCode = row["CorporationCode"].ToString(); //企业代码
                        RWTakeInfoData.corporationName = row["CorporationName"].ToString(); //企业名称
                        RWTakeInfoData.sectionMask = row["SectionMask"].ToString();         //段别标志
                        RWTakeInfoData.detonatorName = row["ProductName"].ToString();       //雷管名称
                        RWTakeInfoData.material = row["MaterialType"].ToString();           //材质
                        RWTakeInfoData.power = row["MaterialWeiLi"].ToString();             //威力
                        RWTakeInfoData.category = row["ProductModel"].ToString();           //类别
                        RWTakeInfoData.FactoryModel = row["FactoryModel"].ToString();       //芯片厂家
                        RWTakeInfoData.notes = row["Remarks"].ToString();                   //备注
                        RWTakeInfoData.permit = row["Permit"].ToString();                   //许可证
                        RWTakeInfoData.SIDTaskNum = row["SIDTaskNum"] == DBNull.Value ? 0 : (int)row["SIDTaskNum"]; ;                 //生产总数
                        RWTakeInfoData.SIDCompleteNum = row["SIDCompleteNum"] == DBNull.Value ? 0 : (int)row["SIDCompleteNum"]; ;         //已生产数量
                        RWTakeInfoData.CurrentTime = ((DateTime)row["CurrentTime"]).ToString("yyyyMMdd"); ;               //当天使用时间
                        RWTakeInfoData.ShengYuQty = row["ShengYuQty"] == DBNull.Value ? 0 : (int)row["ShengYuQty"]; ;                 //已生产数量

                        RWLastListTakeInfoData.Add(RWTakeInfoData);
                    }
                }
                else
                {
                    RWLastListTakeInfoData.Add(RWTakeInfoData);
                }

                DeviceRWLastListTakeInfoData.timeStamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                DeviceRWLastListTakeInfoData.deviceId = device_id;
                DeviceRWLastListTakeInfoData.dataType = "Report";
                DeviceRWLastListTakeInfoData.data = RWLastListTakeInfoData;

                MQTTConsoleServer.Instance.ForwardData(DeviceRWLastListTakeInfoData, "ListTakeInfoData");
            }
            catch (Exception ex)
            {
                Log4NetHelper.Error($"处理所有任务台账异常！ex:{ex}");
                return;
            }
        }
        /// <summary>
        /// 保存报表数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="No"></param>
        /// <param name="device_id"></param>
        /// <param name="dataType"></param>
        /// <param name="ReadData"></param>
        /// <param name="RegisterNumber"></param>
        public static void Report_SaveData<T>(int No, T ReadData)
        {
            ReportData[No].targetCT = ((ReadData as short[])[0] << 16) | ((ReadData as short[])[1] & 0xFFFF);
            ReportData[No].GoodProductCount = ((ReadData as short[])[2] << 16) | ((ReadData as short[])[3] & 0xFFFF);
            ReportData[No].nonGoodProductCount = ((ReadData as short[])[4] << 16) | ((ReadData as short[])[5] & 0xFFFF);
            ReportData[No].alarmCount = (ReadData as short[])[6];
            ReportData[No].ctCount = (ReadData as short[]).Skip(7).Take(10).ToArray();
            ReportData[No].ctAVCount = (ReadData as short[])[17];
            ReportData[No].runTimeStat = (ReadData as short[]).Skip(18).Take(3).ToArray();
            ReportData[No].workTimeStat = (ReadData as short[]).Skip(21).Take(3).ToArray();
            ReportData[No].waitTimeStat = (ReadData as short[]).Skip(24).Take(3).ToArray();
            ReportData[No].alarmTimeStat = (ReadData as short[]).Skip(27).Take(3).ToArray();
            ReportData[No].stopTimeStat = (ReadData as short[]).Skip(30).Take(3).ToArray();
            ReportData[No].workRate = ((ReadData as short[])[33] << 16) | ((ReadData as short[])[34] & 0xFFFF);
            ReportData[No].nonGoodRate = ((ReadData as short[])[35] << 16) | ((ReadData as short[])[36] & 0xFFFF);

            DeviceReportData[No].timeStamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
            DeviceReportData[No].deviceId = AllPLC_Id[No];
            DeviceReportData[No].dataType = "Report";
            DeviceReportData[No].data = ReportData[No];

            //转发数据
            MQTTConsoleServer.Instance.ForwardData(DeviceReportData[No], "DeviceReportData");

        }

        /// <summary>
        /// 保存三色灯状态
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="No"></param>
        /// <param name="ReadData"></param>
        public static void TricolourLight_SaveData<T>(String Devices_Id, T ReadData)
        {
            PublicHelp.DeviceData<PublicHelp.TricolourlightDataModel> DeviceLightDataData = new PublicHelp.DeviceData<PublicHelp.TricolourlightDataModel>();
            PublicHelp.TricolourlightDataModel LightData = new PublicHelp.TricolourlightDataModel();

            LightData.yellow = (ReadData as bool[])[0];
            LightData.green = (ReadData as bool[])[1];
            LightData.red = (ReadData as bool[])[2];

            DeviceLightDataData.timeStamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
            DeviceLightDataData.deviceId = Devices_Id;
            DeviceLightDataData.dataType = "Alarm";
            DeviceLightDataData.data = LightData;

            //转发数据
            MQTTConsoleServer.Instance.ForwardData(DeviceLightDataData, "DeviceLightData");

        }

        /// <summary>
        /// 告警内容MQ转发
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="No"></param>
        /// <param name="ReadData"></param>
        public static void AlarmData_MQ(String Devices_Id, List<AlarmData> ReadData)
        {
            PublicHelp.DeviceData<List<AlarmData>> DeviceAlarmDataData = new PublicHelp.DeviceData<List<AlarmData>>();
           
            DeviceAlarmDataData.timeStamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
            DeviceAlarmDataData.deviceId = Devices_Id;
            DeviceAlarmDataData.dataType = "Alarm";
            //AddressConfigReader.AlarmAddressConfig[] ReadDatas = ReadData as AddressConfigReader.AlarmAddressConfig[];
            DeviceAlarmDataData.data = ReadData ;

            //转发数据
            MQTTConsoleServer.Instance.ForwardData(DeviceAlarmDataData, "DeviceAlarmData");

        }
    }
}
